package org.sensation.file.channel.randomaccess;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.sensation.file.channel.FileWriteChannel;

public class FileWriteChannelRandomAccess implements FileWriteChannel{
	protected File file;
	private RandomAccessFile randomAccessFile;
	
	public FileWriteChannelRandomAccess(String targetFilePath, int targetFileSize)
			throws FileNotFoundException, IOException {
		initRandomAccessFile();
	}

	public void writeFile(ByteBuffer buffer) throws IOException {
		buffer.flip();
		FileChannel targetChannel = getRandomAccessFileChannel(0);
		targetChannel.write(buffer);
	}
	
	public void writeIndexAccessFile(int offset, ByteBuffer buffer) throws IOException{
		FileChannel targetChannel;
		buffer.flip();
		targetChannel = getRandomAccessFileChannel(offset);
		targetChannel.write(buffer);
	}

	private FileChannel getRandomAccessFileChannel(int offset)
			throws IOException {
		FileChannel targetChannel;
		synchronized(randomAccessFile){
			randomAccessFile.seek(offset);
			targetChannel =  randomAccessFile.getChannel();
		}
		return targetChannel;
	}
	
	private void initRandomAccessFile() throws IOException, FileNotFoundException {
		randomAccessFile = new RandomAccessFile(file, "rw");
	}

	public void close() throws IOException {
		if(randomAccessFile != null){
			try {
				randomAccessFile.close();
			} catch (Exception e) {
				randomAccessFile.close();
			}
		}
	}
}
